package com.example.sharingjdbc4digiwin.config;

import com.google.common.collect.Range;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author： ygl
 * @date： 2019/06/23
 * @Description：
 */
@Slf4j
public class TableRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> shardingValue) {
        log.info("分表范围分片算法参数 {},{}", availableTargetNames, shardingValue);
        Collection<String> shardingList = new ArrayList<>();
        Range<String> valueRange = shardingValue.getValueRange();
        String lower = valueRange.lowerEndpoint();
        String upper = valueRange.upperEndpoint();
        int lowerMonth = getMonth(lower);
        int upperMonth = getMonth(upper);
        for (int i = lowerMonth; i <= upperMonth; i++) {
            String table = "data_day_" + i;
            shardingList.add(table);
        }
        log.info("对应的分表：{}",shardingList);
        return shardingList;
    }

    public int getMonth(String shardingKey){
        LocalDate date = LocalDate.parse(shardingKey, formatter);
        Month month = date.getMonth();
        return month.getValue();
    }

}